import { useUserStore } from '@/store/user';
import { toast, tansParams } from '@/utils/common';

export const errorCode = {
  401: '认证失败，无法访问系统资源',
  403: '当前操作没有权限',
  404: '访问资源不存在',
  default: '系统未知错误，请反馈给管理员'
};

function getToken() {
  const userStore = useUserStore();
  return userStore.token;
}

function loginInvalid(){
  const userStore = useUserStore();
  userStore.loginInvalid()
}

export let timeout = 10000;
// export const baseUrl = 'http://ai.zjtg.com.cn:8018';
export const baseUrl = process.env.NODE_ENV == 'development' ? 'http://ai.zjtg.com.cn:8018' : 'http://ai.zjtg.com.cn:8020';  
// export const baseUrl = 'http://172.16.28.13:8081';  //康闪

export const request = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};

  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken();
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  return new Promise((resolve, reject) => {
    const reqConfig = {
      method: config.method || 'get',
      timeout: config.timeout || timeout,
      url: config.baseUrl || baseUrl + config.url,
      data: config.data,
      header: config.header,
      dataType: 'json'
    };
    // console.log('reqConfig',reqConfig);
    
    uni
      .request(reqConfig)
      .then(response => {
        // console.log('response',response);
        
        const res = response;
        const code = res.data.code || 200;
        const msg = res.data.msg || errorCode[code] || errorCode['default'];
        if (code === 401) {
          toast(msg || '无效的会话，或者会话已过期，请重新登录。');
          loginInvalid()
          reject(res);
        } else if (code === 500) {
          toast(msg);
          reject(res);
        } else if (code !== 200) {
          toast(msg);
          reject(res);
        }
        resolve(res.data);
      })
      .catch(error => {
        // console.log('error',error);
        
        // 纯原生错误处理（不添加任何额外属性）
        let message = error.errMsg || '请求失败';

        const lingxinrenMsg = '请检查零信任是否开启';

        if (message.includes('timeout')) {
          message = `请求超时，${lingxinrenMsg}`;
        } else if (message.includes('fail') && message.includes('url')) {
          message = `网络连接失败，${lingxinrenMsg}`;
        } else if (message.includes('abort')) {
          if (message.includes('Unable to resolve host') || message.includes('No address associated')) {
            message = `网络连接失败，${lingxinrenMsg}`;
          } else {
            // 手动取消的请求（不显示Toast）
            return reject(error);
          }
        }

        toast(message);
        reject(error); // 原样传递错误对象
      });
  });
};

/**
 * GET请求
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @param {object} headers 请求头
 * @param {number} customTimeout 自定义超时时间
 * @returns {Promise}
 */
export const get = (url, params = {}, headers = {}, customTimeout = null) => {
  return request({
    method: 'get',
    url,
    params,
    header: headers,
    timeout: customTimeout
  });
};

/**
 * POST请求
 * @param {string} url 请求地址
 * @param {object} data 请求体数据
 * @param {object} headers 请求头
 * @param {number} customTimeout 自定义超时时间
 * @returns {Promise}
 */
export const post = (url, data = {}, headers = {}, customTimeout = null) => {
  return request({
    method: 'post',
    url,
    data,
    header: headers,
    timeout: customTimeout
  });
};

export default {
  request,
  get,
  post
};
